import requests
import json
import logging
import os
from dotenv import load_dotenv
logger = logging.getLogger(__name__)

# 加载.env文件
load_dotenv()

# 从环境变量获取敏感信息
url = os.environ.get('POPO_URL')
appid = os.environ.get('POPO_APPID')
appSecret = os.environ.get('POPO_APPSECRET')

# 请求头
headers = {
    'Content-Type': 'application/json'
}

# 获取Token的函数，注意Token的有效期为24小时
def GetToken():
    # 请求的payload
    payload = {
        "appId": appid,
        "appSecret":appSecret
    }
    try:
        # 使用POST方法进行调用
        response = requests.post(url, headers=headers, data=json.dumps(payload))

        # 检查响应状态码
        if response.status_code == 200:
            # 解析响应内容
            response_json = response.json()
            print(response_json)
            token = response_json.get('data', {}).get('openAccessToken', None)
            #expiretime = response_json.get('data', {}).get('accessExpiredAt', None) 

            if token:
                print(f'获取到的token: {token}')
                logger.info(f'token已更新: {token}')
                return token
                
            else:
                print('无法获取token')
                logger.info(f'无法获取token')
        else:
            print(f'请求失败，状态码：{response.status_code}')
            logger.info(f'请求失败，状态码：{response.status_code}')
    except Exception as e:
        print(f"出现错误: {str(e)}")
        logger.error(f"出现错误: {str(e)}", exc_info=True)

GetToken()
